package cn.com.zsw.gblog.modules.common.contrller;

import cn.com.zsw.gblog.config.MongoGridFsDao;
import cn.com.zsw.gblog.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-07-22 19:50
 * @Description： 文件控制器
 */
@RestController
@RequestMapping("file")
@Slf4j
@Api(tags = "博客", value = "FileController")
public class FileController {
    @Autowired
    MongoGridFsDao mongoGridFsDao;


    @Value("${file.download.domain}")
    private String fileDownloadUrl;


    @GetMapping("download")
    @ApiOperation("文件下载")
    public void download(String fileId, HttpServletResponse response) throws Exception {
        InputStream inputStream = mongoGridFsDao.downloadByObjectId(fileId);
        if (inputStream != null) {
            File file = new File("D:\\sd.jpg");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + file.getName());
            IOUtils.copy(inputStream, response.getOutputStream());
        }

    }

    @PostMapping("upload")
    @ApiOperation("文件上传")
    public R upload(MultipartFile file) throws Exception {
        String s = mongoGridFsDao.uploadFile(file);
        s = fileDownloadUrl + "/file/download?fileId=" + s;
        return R.SUCCESS.msg("文件上传成功").data(s);
    }
}
